package me.shan.sort.merge;

import java.util.Arrays;

/**
 * 描述：
 *
 * @author liuchuang
 * @date 2021/8/6 16:12
 */
public class MergeSort {

    public static void sort(int[] array) {
        mergeSort(array);
    }

    /**
     * 归并排序递归版
     *
     * @param array 数组
     * @param left  左边界
     * @param right 右边界
     */
    private static void mergeSort(int[] array, int left, int right) {
        if (left >= right) {
            return;
        }
        int mid = left + ((right - left) >> 1);
        mergeSort(array, left, mid);
        mergeSort(array, mid + 1, right);
        merge(array, left, mid, right);
    }

    /**
     * 递归版归并
     *
     * @param array 待排序数组
     * @param l     左边界
     * @param m     中点
     * @param r     右边界
     */
    private static void merge(int[] array, int l, int m, int r) {
        int[] temp = new int[r - l + 1];
        int i = l, j = m + 1, k = 0;
        while (i <= m && j <= r) {
            if (array[i] <= array[j]) {
                temp[k] = array[i];
                i++;
            } else {
                temp[k] = array[j];
                j++;
            }
            k++;
        }
        while (i <= m) {
            temp[k] = array[i];
            k++;
            i++;
        }
        while (j <= r) {
            temp[k] = array[j];
            k++;
            j++;
        }
        System.arraycopy(temp, 0, array, l, temp.length);
    }

    /**
     * 归并排序迭代版
     *
     * @param array 待排序数组
     */
    private static void mergeSort(int[] array) {
        int step = 1;
        int size = array.length;
        while (step < size) {
            for (int i = 0; i < size - step; i += 2 * step) {
                mergeV2(array, i, step);
            }
            if (step > size >> 1) {
                break;
            }
            step <<= 1;
        }
    }

    /**
     * 迭代版归并
     *
     * @param array 原始数组
     * @param l     左边开始下标
     * @param step  步长
     */
    private static void mergeV2(int[] array, int l, int step) {
        int r = Math.min(array.length, l + 2 * step) - 1;
        merge(array, l, l + step - 1, r);
    }

    public static void main(String[] args) {
        int[] array = {2, 4, 6, 1, 3, 5, 7, 3, 2, 8, 9, 1, 7, 3, 6, 0, 5, 2};
        int[] temp = new int[array.length];
        System.arraycopy(array, 0, temp, 0, temp.length);
        sort(array);
        System.out.println(Arrays.toString(array));
        Arrays.sort(temp);
        System.out.println(Arrays.toString(temp));
    }

}
